package com.lzy.service;

import com.lzy.spring.BeanPostProcessor;
import com.lzy.spring.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

// 后置处理器
@Component
public class LzyBeanPostProcess implements BeanPostProcessor {

	@Override
	public Object postProcessBeforeInitialization(String beanName, Object bean) {
		if("userService".equals(beanName)) {
			System.out.println("userService --- postProcessBeforeInitialization" + bean.getClass());

			// 使用jdk的动态代理技术
			return  Proxy.newProxyInstance(bean.getClass().getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {

				/**
				 * 去执行本来的对象的方法。
				 * @param proxy 这个是我们的代理对象
				 * @param method
				 * @param args
				 * @return
				 * @throws Throwable
				 */
				@Override
				public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
					System.out.println("invoke---");
					return method.invoke(bean, args);
				}
			});

		}
		return bean;
	}

	@Override
	public Object postProcessAfterInitialization(String beanName, Object bean) {
		if("userService".equals(beanName)) {
			System.out.println("userService --- postProcessAfterInitialization" + bean.getClass());
		}

		return bean;
	}
}
